import sel from '../../index.js';
import E from '../../direct/effect.js';
import './tree.scss';

export default {
  init:function () {
    sel.app.controller('treeController',['$scope','$http',
    function ($scope, $http) {
      $scope.title = '捆绑图';
      //绘画
       let pad =  sel.d3.select('.contain').append('svg')
        .attr('width',1000)
        .attr('height',1000)
        ;
      $http.get('api/tree').then(function (data) {
        $scope.nodes = data.data.data.data.ciNodes;
        $scope.lines = data.data.data.data.ciRltLines;
        $scope.class = data.data.data.data.ciClassInfos;
      })
      ;
      //进行绘图
       $scope.show = function(){
         pad.html("");
         let padCotainer = pad.append('g');
         //加入箭头
         padCotainer
         .append('defs')
         .append('marker')
         .attr('id', 'arrow')
         .attr('viewBox', '0 -5 10 10')
         .attr('refX', 10)
         .attr('refY', 0)
         .attr('markerWidth', 5)
         .attr('markerHeight', 5)
         .attr('orient', 'auto')
         .append('path')
         .attr('d','M0,-5L10,0L0,5')
         .attr('fill','#ccc')
         ;
         //进行缩放处理
         let objs = sel.d3.zoomTransform(padCotainer);
         objs.x = 40;
         objs.y = 40;
         objs.k = 1;
         let zoom = sel.d3.zoom().on('zoom',()=>padCotainer.attr('transform', sel.d3.event.transform));
         pad.call(zoom);
         zoom.transform(padCotainer,objs);
         //特效
         let lightEffect ;

         let fouced = function (data) {
           if(data.children){
             return
           };
           lightEffect = E.light().radius(5).speed(100).color(function (d) {
             return d.source.data.classColor || 'green'
           });
           padCotainer
             .selectAll('.rlt-lines')
             .classed('focused',false)
             .transition('focus')
             .duration(200)
             .style('opacity','0.2')
             .attr('stroke-width',1)
           ;
           padCotainer.selectAll('.rlt-lines')
           .filter(function (d) {
             return d.source.x == data.x || d.target.x == data.x;
           })
           .classed('focused',true)
           .interrupt('focus')
           .style('opacity','1')
           .attr('stroke-width',4)
           .call(lightEffect)
           ;
         };
         let cancelfouced = function (d) {
           lightEffect && lightEffect.clear();
           padCotainer
           .selectAll('.rlt-lines')
           .classed('focused',false)
           .interrupt('focus')
           .style('opacity','1')
           .attr('stroke-width',1)
           ;
         };
         //转换数据
         let num = $scope.class.length;
         for(let i = 0; i < $scope.class.length; i++) {
           for(let j = 0; j < $scope.nodes.length; j++) {
             if($scope.class[i].ciClass.id == $scope.nodes[j].classId){
               if(!$scope.class[i].children){
                 $scope.class[i].children = [];
               }
               $scope.class[i].children.push($scope.nodes[j]);
             }
           }
         };
         let dataNode = {};
         dataNode.name = '树形图';
         dataNode.children =  $scope.class;


         let tree = sel.d3.tree().size([4000,400]).separation(function (a,b) {
           return (a.parent == b.parent?1:2)
         });
         dataNode = sel.d3.hierarchy(dataNode);

         let nodes = tree(dataNode);
         let nodeG = padCotainer.selectAll('.node').data(nodes.descendants()).enter().append('g').attr('class',function (d) {
           return ('node ' + (d.children?'node-parent':'node-leaf'))
         });
         nodeG
         .append('circle')
         .attr('r',20)
         .attr('cx',function(d){
           return d.x
         })
         .attr('cy',function(d){
           return d.y
         })
         .attr('fill',function (d) {
           return d.parent?(d.data.classColor || d.data.ciClass.classColor):'#fff'
         })
         .on('mouseenter',fouced)
         .on('mouseout',cancelfouced)
         ;
         nodeG.append('text')
         .attr('dx',function(d){
           return d.x
         })
         .attr('dy',function(d){
           return (d.y+13)
         })
         .attr('y',function(d){
           return d.data.children?-8:8
         })
         .attr('writing-mode',"tb")
         .style("text-anchor", function(d) { return d.data.children ? "end" : "start"; })
         .text(function (d) {
           return(d.data.name || d.data.ciCode||d.data.ciClass.classCode )
         })
         ;

         //添加线
         let links = nodes.descendants().slice(1);
         padCotainer
           .selectAll('.links')
           .data(links)
           .enter()
           .append('path')
           .attr('class','links')
           .attr('fill','none')
           .attr('stroke','black')
           .attr('d',function(d){
             return "M" + d.x + "," + d.y
             + "C" + (d.x + d.parent.x) / 2 + "," + d.y
             + " " + (d.x + d.parent.x) / 2 + "," + d.parent.y
             + " " + d.parent.x + "," + d.parent.y;
           })
         ;

         let allCi = links.slice(num);
         for(let i = 0; i < $scope.lines.length; i++) {
           for(let j = 0; j < allCi.length; j++) {
             if( $scope.lines[i].target == allCi[j].data.id ) {
               $scope.lines[i].target =  allCi[j];
             }else if ( $scope.lines[i].source == allCi[j].data.id ) {
               $scope.lines[i].source =  allCi[j];
             }
           }
         };
         //进行绘线
        let rltLines =  padCotainer.append('g').attr('class','rlt');


       //进行分批画线（根据不同target进行画线）(此效果有待提升)
       /**   let sort = {};
         for(var i = 0 ; i <$scope.lines.length; i++ ){
           if(!sort[$scope.lines[i].source.data.id]){
             sort[$scope.lines[i].source.data.id] = [];
           }
           sort[$scope.lines[i].source.data.id].push($scope.lines[i]);
         };
         console.log(sort);
        for(var i in sort) {
          let name = 'rlt'+i;
          sort[i].sort(function (a,b) {
            return a.target.x - b.target.x
          });
          drawAddLine(sort[i],name)
        };
        //画线
         function drawAddLine(arr,name) {
           let i = 1;
           let className = '.'+name;
           rltLines.selectAll(className)
           .data(arr)
           .enter()
           .append('path')
           .attr('class','rlt-line '+name)
           .attr("d",function (d) {
             return drawData(d,i++);

           })
           .attr('fill','none')
           .attr('stroke',function (d) {
             return d.source.data.classColor;
           })

           ;

         };
         function drawData(obj,i) {
            let num = 50*i;
            let begin = 'M'+ obj.source.x + ","+ obj.source.y;
            let to1 = 'L' + obj.source.x + ","+ (obj.source.y + num);
            let to2 = 'L'+ obj.target.x + ","+ (obj.target.y + num);
            let end = 'L'+ obj.target.x + ","+ obj.target.y;
            return begin + to1 + to2 + end;
         };

      **/
       //进行曲线绘画

      let lineData = sel.d3.line().curve(sel.d3.curveBundle.beta(10));
      let middle = function (obj) {
        let x = obj.source.x;
        let y = obj.target.x;
        let middles = (x - y)/2 + y;
        if(y > x){
          middles = (y - x )/2 + x ;
        }
        return middles;

      };

         rltLines.selectAll('rlt-lines')
           .data($scope.lines)
           .enter()
           .append('g')
           .append('path')
           .attr('class','rlt-lines')
           .attr('fill','none')
           .attr('stroke',function (d) {
             return d.source.data.classColor || 'blue'
           })
           .attr('d',function (d) {
             return lineData([[d.source.x,d.source.y+20],[middle(d),d.source.y + 50],[d.target.x,d.target.y+20]]);

           })
           .attr('marker-end', 'url(#arrow)')
         ;


       };










    }])
  }
}